package com.db.ionio.io;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class FileIOServer {
    private final int port;
    private final String dstFileName;

    public FileIOServer(int port, String dstFileName) {
        this.port = port;
        this.dstFileName = dstFileName;
    }

    public void run() {
        System.out.println("Waiting for client connection ...");
        try (ServerSocket socketFactory = new ServerSocket(port);
             Socket socket = socketFactory.accept();
             PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
             DataInputStream input = new DataInputStream(socket.getInputStream());
             FileOutputStream out = new FileOutputStream(new File(dstFileName));) {

            long fileSize = input.readLong();
            System.out.format("file size is %d%n", fileSize);

            final int bufferSize = 32 * 1024;
            final byte[] buffer = new byte[bufferSize];
            int currentBytesRead = 0;

            while (currentBytesRead != fileSize) {
                int bytesRead = input.read(buffer, 0, buffer.length);
                currentBytesRead += bytesRead;
                out.write(buffer, 0, bytesRead);
            }
            System.out.println("done");
            output.println("done");

        } catch (IOException ioException) {
            ioException.printStackTrace();
            System.err.println(ioException.getMessage());
        } catch (NullPointerException nullPointerException) {
            nullPointerException.printStackTrace();
            System.err.println(nullPointerException.getMessage());
        }
    }
}

